package com.igroupes.ovineherd.model.attribute.text;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import com.igroupes.ovineherd.entity.DataModelAttributeEntity;
import com.igroupes.ovineherd.enums.BooleanKey;
import com.igroupes.ovineherd.model.IParentModelData;
import com.igroupes.ovineherd.model.Style.TextStyle;
import com.igroupes.ovineherd.model.dto.FieldApiResponse;
import com.igroupes.ovineherd.model.enums.MySqlTypeKey;
import com.igroupes.ovineherd.query.FieldQuery;
import com.igroupes.ovineherd.query.ModelDataJsonAttributeQuery;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

import java.util.List;

/**
 * 自定义小文本
 */
@EqualsAndHashCode(callSuper = true)
@Data
@ToString(callSuper = true)
public class TextModelData extends TextBasicAttribute{

    public TextModelData() {
        super();
    }

    public Boolean verifyField(TextModelData json) {
        return super.verifyField(json);
    }

    @Override
    public List<FieldQuery> sqlField(IParentModelData parentModelData, DataModelAttributeEntity dataModelAttributeEntityOld) {
        TextModelData textModelData = (TextModelData) parentModelData.getAttributes();
        List<FieldQuery> fieldQueries = super.sqlField(parentModelData,dataModelAttributeEntityOld);
        FieldQuery fieldQuery = fieldQueries.get(0);
        Integer length = Convert.toInt(textModelData.getMaxLength().getValue());
        if(length > 1500){
            fieldQuery.setType(MySqlTypeKey.TEXT.getCode());
        }else{
            fieldQuery.setType(MySqlTypeKey.VARCHAR.getCode());
            fieldQuery.setLength(length);
        }
        fieldQueries.set(0,fieldQuery);
        return fieldQueries;
    }
    @Override
    public JSONObject getAttribute(ModelDataJsonAttributeQuery modelDataJsonAttributeQuery) {
        return super.getAttribute(modelDataJsonAttributeQuery);
    }
    @Override
    public List<FieldApiResponse> verifyRequestData(DataModelAttributeEntity modelAttributeEntity, Object value) {
        List<FieldApiResponse> fieldApiResponses = super.verifyRequestData(modelAttributeEntity, value);
        if(value == null){
            return fieldApiResponses;
        }

        FieldApiResponse fieldApiResponse = fieldApiResponses.get(0);
        fieldApiResponse.setDbName(modelAttributeEntity.getDbName());
        fieldApiResponse.setValue(value);
        fieldApiResponse.setIsStr(true);
        fieldApiResponse.setType(MySqlTypeKey.VARCHAR.getCode());
        fieldApiResponses.set(0,fieldApiResponse);
        return fieldApiResponses;
    }
    @Override
    public JSONObject getAttributeStyle(ModelDataJsonAttributeQuery dataModelAttributeEntity) {

        return new JSONObject(new TextStyle(
                dataModelAttributeEntity.getName(),"",
                dataModelAttributeEntity.getIsNull().equals(BooleanKey.TRUE.getCode())
        ), false);
    }
}
